import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/login/index.vue';
import { getToken } from '@/utils/token';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      name: 'admin',
      meta: {
        title: '首页',
        auth: true,
      },
      redirect: '/user',
      component: () => import('../views/admin/index.vue'),
      children: [
        {
          path: '/user',
          meta: {
            title: '用户管理',
          },
          redirect: '/user/index',
          children: [
            {
              path: '/user/index',
              meta: {
                title: '用户列表',
              },
              component: () => import('../views/admin/user/index.vue'),
            },
          ],
        },
      ],
    },
  ],
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((item) => item.meta.auth)) {
    const token = getToken();
    if (token) {
      return next();
    } else {
      return next({
        name: 'login',
        query: {
          redirect: to.fullPath,
        },
      });
    }
  } else {
    return next();
  }
});

export default router;
